<template>
  <div class="page-body course-page">
    <nav class="courses-nav">
      <ul class="courses-navbar">
        <li v-for="category in navCategoriesList.data" :key="category._id" class="nav-item"
          :class="uid === category._id?'nav-item-active':''">
          <router-link tag="a" :to="category._id === '5555555aaa5555555' ? '/courses':`/channel/${category._id}`"
            class="font-gray-1 fs-md">{{ category.name }}</router-link>
        </li>
      </ul>
      <ul class="courses-option-navbar">
        <li v-for="(category,index) in childCategoriesList.data" :key="category._id" class="nav-item">
          <router-link tag="a"
            :to="category._id === '444444bbb444444' ? `/channel/${uid}`:`/channel/${uid}/${category._id}`"
            class="font-gray-1 fs-sm"
            :class="pid === category._id?'nav-opt-item-active':!pid&&index===0?'nav-opt-item-active':''">
            {{ category.name }}</router-link>
        </li>
      </ul>
    </nav>
    <div class="course-page-body d-flex">
      <div class="course-page-left col-lg-9">
        <div class="course-carousel"
          :class="[isCarouselShow ? 'carousel-hidden' : '',uid!=='5f799255a3a37d67642a3b0e'?'carousel-hidden':'']">
          <a-carousel :dots="false" autoplay effect="scrollx" :vertical="true">
            <div>
              <img src="http://image.howzhi.com/system/block_picture_1460094695.jpg" alt="" />
            </div>
            <div>
              <img src="http://image.howzhi.com/system/block_picture_1460533852.jpg" alt="" />
            </div>
          </a-carousel>
          <span class="close-carousel" @click="closeCarousel">x</span>
        </div>
        <nav class="sort-nav">
          <ul class="sort-navbar">
            <li class="nav-item">
              <a href=""><span>综合排序</span></a>
            </li>
            <li class="nav-item">
              <a href=""><span>最新</span></a>
            </li>
            <li class="nav-item">
              <a href=""><span>最热</span></a>
            </li>
            <li class="nav-item">
              <a href=""><span>价格排序<i class="iconfont icon-arrowdown"></i></span></a>
            </li>
            <li class="nav-item">
              <a href="">
                <span>
                  <i class="iconfont icon-check-box-outline-bl icon_default_show"></i>
                  <i class="iconfont icon-check_box_px_rounded icon_hidden"></i>
                  直播课</span>
              </a>
            </li>
            <li class="nav-item">
              <a href="">
                <span>
                  <i class="iconfont icon-check-box-outline-bl icon_default_show"></i>
                  <i class="iconfont icon-check_box_px_rounded icon_hidden"></i>
                  收费课程</span>
              </a>
            </li>
          </ul>
        </nav>
        <div class="courses-list">
          <div class="courses-list-show" style="display:flex;">
            <div class="col-lg-4 col-md-6" v-for="item in (pid?currentChildCourseList.data:showCourses)"
              :key="item._id">
              <div class="courses-item">
                <div class="img-container">
                  <img src="../../assets/default.jpg" class="image-item" lazyload="true" :data-original="item.image"
                    alt="" />
                </div>
                <div class="courses-other">
                  <p class="courses-title">{{item.title}}</p>
                  <div class="courses-info d-flex font-light fs-xs">
                    <span>{{item.readed > 10000 ? `${Math.floor(item.readed / 10000)}万+浏览`:`${item.readed}浏览`}}</span>
                    <span class="span-line">/</span>
                    <span>{{item.students+'学员'}}</span>
                    <span class="span-line">/</span>
                    <span>{{item.score+'评分'}}</span>
                  </div>
                  <div class="courses-about d-flex">
                    <div class="author-info">
                      <img class="author-avatar" :src="item.author.avatar" alt="">
                      <span>{{item.author.name}}</span>
                    </div>
                    <div class="courses-price" :class="item.price === 0 ? 'free' : 'expensive'">
                      {{item.price === 0 ? '免费' :`￥${item.price}` }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <a-pagination :hideOnSinglePage="true" v-model:current="currentPage" @change="paginationChange"
            :total="(pid?currentChildCourseList.data:allCoursesList.data)?.length" :page-size="18" />
        </div>
      </div>
      <SlideCoursesList class="col-md-3" :slideCoursesData="slideCoursesData"></SlideCoursesList>
    </div>
  </div>
</template>

<script>
import { getAllCoursesCategories, getAllCourses, getCurrentCourses, getChildCategories, getChildCourses } from '../../api'
import { onMounted, reactive, ref, computed, watch } from 'vue'
import SlideCoursesList from '../SlideCoursesList'
import Router from '../../router'
export default {
  props: ['uid', 'pid'],
  components: { SlideCoursesList },
  setup (props) {
    // 获取二级分类
    const navCategoriesList = reactive({
      data: []
    })
    // 获取二级分类下的子级分类
    const childCategoriesList = reactive({
      data: []
    })
    // 获取所有课程列表
    const allCoursesList = reactive({
      data: []
    })
    const currentChildCourseList = reactive({
      data: []
    })
    // 轮播广告位是否展示
    const isCarouselShow = ref(false)
    // 分页器当前的页数
    const currentPage = ref(1)
    // 当前页面所要展示的课程列表
    const currentCourseList = reactive({
      data: []
    })
    // 随机推荐课程的课程列表
    const slideCoursesData = reactive({
      data: []
    })
    // 获取分页长度
    const Paginationlength = computed(() => {
      return Math.ceil(allCoursesList.data?.length / 18)
    })
    onMounted(async () => {
      // 获取所有课程分类
      const res = await getAllCoursesCategories()
      navCategoriesList.data = res.data
      // console.log(navCategoriesList.data)

      // 获取当前分类的课程
      const coursesRes = await getCurrentCourses(props.uid)
      console.log(coursesRes)
      allCoursesList.data = coursesRes.data

      // 获取二级分类下的子级分类
      const categoriesRes = await getChildCategories(props.uid)
      childCategoriesList.data = categoriesRes.data
      // console.log(allCoursesList.data)

      // 获取对应子级分类的课程
      if (props.pid) {
        const currentCoursesRes = await getChildCourses(props.pid)
        currentChildCourseList.data = currentCoursesRes.data
        console.log(currentChildCourseList.data)
      }

      // 获取随机推荐课程
      if (props.pid) {
        slideCoursesData.data = currentChildCourseList.data.splice(Math.floor(Math.random() * currentChildCourseList.data.length - 3), 3)
        console.log(slideCoursesData.data)
      } else {
        const random = (Math.floor(Math.random() * allCoursesList.data.length)) - 6
        slideCoursesData.data = allCoursesList.data.slice(random, random + 6)
        console.log(slideCoursesData.data)
      }
      setTimeout(() => {
        lazyload()
      })
    })

    // 计算属性
    const showCourses = computed(() => {
      const newArr = deepclone(allCoursesList.data)
      const index = (currentPage.value - 1) * 18
      return newArr.splice(index, 18)
    })

    // 组件方法
    function closeCarousel () {
      isCarouselShow.value = !isCarouselShow.value
    }

    // 分页方法
    function paginationChange (page, pageSize) {
      currentPage.value = page
      // console.log(page, pageSize)
      // Router.push(`/courses/${page}`)
      // pageScroll()
      window.scrollTo(0, 0)
    }

    // 深拷贝
    function deepclone (obj) {
      var obj2 = obj instanceof Array ? [] : {}
      for (const [k, v] of Object.entries(obj)) {
        obj2[k] = typeof v === 'object' ? deepclone(v) : v
      }
      return obj2
    }

    // 图片懒加载
    function lazyload () {
      const scrollY = document.documentElement.scrollTop
      const offsetHeight = document.documentElement.offsetHeight
      const imgs = document.querySelectorAll('img[data-original][lazyload]')
      imgs.forEach(item => {
        if (item.dataset.original === '') {
          return
        }
        const rect = item.getBoundingClientRect()
        if (rect.bottom >= 0 && rect.top < scrollY + offsetHeight) {
          const img = new Image()
          img.src = item.dataset.original
          // console.log(img.src)
          img.onload = function() {
            item.src = img.src
          }
          item.removeAttribute('data-original')
          item.removeAttribute('lazyload')
        }
      })
    }
    document.addEventListener('scroll', lazyload)

    return {
      navCategoriesList,
      isCarouselShow,
      closeCarousel,
      allCoursesList,
      Paginationlength,
      paginationChange,
      currentPage,
      showCourses,
      childCategoriesList,
      currentChildCourseList,
      slideCoursesData
    }
  }
}
</script>

<style lang="scss" scoped>
.course-page {
  margin: 30px auto;
  .courses-nav {
    .courses-navbar {
      background-color: #f9f9f9;
      list-style: none;
      display: flex;
      justify-content: space-evenly;
      border: 1px solid #f0f0f0;
      border-bottom: none;
      margin-bottom: 0;
      .nav-item {
        flex: 1;
        box-sizing: border-box;
        text-align: center;
        border-bottom: 1px solid #f0f0f0;
        a {
          display: inline-block;
          padding: 22px 0;
        }
        &.nav-item-active {
          background-color: #fff;
          border-top: 2px solid #15c288;
          border-bottom: none;
        }
      }
    }
    .courses-option-navbar {
      background-color: #fff;
      list-style: none;
      border: 1px solid #f0f0f0;
      border-top: none;
      width: 100%;
      height: 64px;
      .nav-item {
        float: left;
        box-sizing: border-box;
        width: 10%;
        text-align: center;
        a {
          display: inline-block;
          padding: 22px 0;
          &.nav-opt-item-active {
            color: #15c288 !important;
          }
        }
      }
    }
    margin-bottom: 20px;
  }
  .course-page-body {
    .course-page-left {
      &.col-lg-9 {
        padding: 0 10px !important;
      }
      box-sizing: border-box;
      .course-carousel {
        display: inline-block;
        position: relative;
        margin-bottom: 20px;
        &.carousel-hidden {
          display: none;
        }
        .close-carousel {
          position: absolute;
          top: 3px;
          right: 10px;
          color: #ccc;
          font-size: 20px;
          font-weight: bold;
          text-shadow: 0 1px 0 #fff;
          cursor: pointer;
        }
      }
      .sort-nav {
        .sort-navbar {
          list-style: none;
          display: flex;
          background-color: #f9f9f9;
          border: 1px solid #f0f0f0;
          .nav-item {
            padding: 9px 25px;
            .icon-arrowdown {
              font-size: 10px;
              padding-left: 2px;
            }
            a {
              color: #666;
            }
            .icon_default_show {
              color: white;
              border: 1px solid #f0f0f0;
              background-color: #fff;
              font-size: 10px;
            }
            .icon_hidden {
              display: none;
            }
          }
        }
      }
      .courses-list {
        margin-left: -10px;
        margin-right: -10px;
        .courses-list-show {
          flex-wrap: wrap;
        }
        .col-lg-4 {
          padding: 0 10px !important;
          .courses-item {
            .img-container {
              overflow: hidden;
              .image-item {
                width: 100%;
                height: 151.88px;
                background-color: #ccc;
                transition: all 0.4s ease;
                &:hover {
                  transform: scale(1.2);
                }
              }
            }
            .courses-other {
              padding: 12px 5px;
              .courses-title {
                font-weight: 600;
                margin: 0 0 10px !important;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
              .courses-info {
                margin-bottom: 10px;
                .span-line {
                  padding: 0 7px 0;
                }
              }
              .courses-about {
                justify-content: space-between;
                margin-bottom: 10px;
                .author-info {
                  .author-avatar {
                    width: 20px;
                    height: 20px;
                    border-radius: 50%;
                    margin-right: 4px;
                    position: relative;
                    bottom: 1px;
                  }
                }
                .courses-price {
                  &.free {
                    color: #15c288;
                  }
                  &.expensive {
                    color: #fd9271;
                  }
                }
              }
            }
          }
        }
        .ant-pagination {
          display: block;
          margin: 20px 0;
          text-align: center;
        }
        // .ant-pagination-item-link .anticon {
        //   position: relative !important;
        //   bottom: 2px !important;
        // }
      }
    }
  }
}
</style>
